import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 注销用户功能
 * 要求用户输入用户名 和 密码
 * 结果:
 *   1.注销成功
 *   2.用户名或密码错误
 *   SELECT username,password,nickname,age FROM userinfo WHERE username=? AND password=?
 *   DELETE FROM userinfo WHERE username=?
 */
public class JDBCDeleteUser {
    public static void main(String[] args) {
        //接收用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("注销用户功能");
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        // 数据库操作
        try (Connection connection = DBUtil.getConnection();){
            String sql1 = "SELECT id FROM userinfo WHERE username=? AND password=?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, username);
            ps1.setString(2, password);
            ResultSet resultSet = ps1.executeQuery();
            //判断resultSet
            if(resultSet.next()){
                //注销用户逻辑
                String sql2 = "DELETE FROM userinfo WHERE username=?";
                PreparedStatement ps2 = connection.prepareStatement(sql2);
                ps2.setString(1, username);
                // DML:executeUpdate()
                int i = ps2.executeUpdate();
                if (i > 0){
                    System.out.println("注销用户成功");
                }else{
                    System.out.println("服务器繁忙,请稍后再试");
                }
            }else {
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}









